<template>
  <div class="quality-inspection">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <h2>质量检测NGOK</h2>
      <el-button type="primary" @click="handleOpenDialog">新增检测数据</el-button>
    </div>

    <!-- 查询区域 -->
    <div class="search-container" style="margin-bottom: 20px; padding: 16px; background: #f5f7fa; border-radius: 8px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select
            v-model="searchForm.TestName"
            placeholder="请选择检测项目"
            style="width: 100%"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="item in inspectionItemOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.Lot"
            placeholder="请输入批次号"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.TestPerson"
            placeholder="请选择检测人员"
            style="width: 100%"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="item in inspectorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchForm.isUploaded"
            placeholder="请选择上传状态"
            style="width: 100%"
          >
            <el-option label="全部" value="" />
            <el-option label="已上传" value="已上传" />
            <el-option label="未上传" value="未上传" />
          </el-select>
        </el-col>
        <el-col :span="24" style="text-align: right; margin-top: 10px;">
          <el-button type="primary" @click="fetchTableData">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 数据列表表格 -->
    <el-table
      :data="filteredTableData"
      border
      stripe
      style="width: 100%"
      :loading="tableLoading"
      height="calc(100vh - 240px)"
      max-height="calc(100vh - 240px)"
      :header-cell-style="{ 'position': 'sticky', 'top': '0', 'z-index': 10 }"
    >
      <el-table-column
        prop="TestName"
        label="检测项目"
        align="center"
        width="180"
      >
        <template #default="scope">
          {{ getInspectionItemLabel(scope.row.TestName) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="Lot"
        label="批次号"
        align="center"
        width="180"
      />
      <!-- 检测结果列 - 已添加颜色 -->
      <el-table-column
        prop="TestData"
        label="检测结果"
        align="center"
        width="120"
      >
        <template #default="scope">
          <span :class="scope.row.TestData === 'OK' ? 'text-green-600 font-bold' : 'text-red-600 font-bold'">
            {{ getTestResultLabel(scope.row.TestData) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="TestPerson"
        label="检测人员"
        align="center"
        width="150"
      >
        <template #default="scope">
          {{ getInspectorLabel(scope.row.TestPerson) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="TestTime"
        label="测试时间"
        align="center"
        width="200"
      />
      <el-table-column
        prop="isUploaded"
        label="是否上传"
        align="center"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="scope.row.isUploaded === '已上传' ? 'success' : 'warning'">
            {{ scope.row.isUploaded }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" style="color: #409eff" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="isEditMode ? '编辑检测数据' : '新增检测数据'"
      v-model="addDialogVisible"
      width="900px"
      append-to-body
      :modal="true"
      :close-on-click-modal="false"
    >
      <!-- 新增模式下的检测项目和检测人员选择行 -->
      <div v-if="!isEditMode" class="batch-header" style="margin-bottom: 15px; display: flex; gap: 20px;">
        <el-form-item label="检测项目" style="margin: 0; flex: 1;">
          <el-select
            v-model="batchForm.TestName"
            placeholder="请选择检测项目"
            style="width: 100%"
            required
          >
            <el-option
              v-for="item in inspectionItemOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检测人员" style="margin: 0; flex: 1;">
          <el-select
            v-model="batchForm.TestPerson"
            placeholder="请选择检测人员"
            style="width: 100%"
            required
          >
            <el-option
              v-for="item in inspectorOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- 批量新增表格 -->
      <el-table
        :data="addTableData"
        border
        style="width: 100%; margin-bottom: 20px"
        @selection-change="handleSelectionChange"
      >
        <!-- 编辑模式显示检测项目和检测人员列 -->
        <el-table-column
          v-if="isEditMode"
          label="检测项目"
          align="center"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.TestName"
              placeholder="请选择检测项目"
              style="width: 100%"
              required
            >
              <el-option
                v-for="item in inspectionItemOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="批次号"
          align="center"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.Lot"
              placeholder="请输入批次号"
              style="width: 100%"
              required
            />
          </template>
        </el-table-column>
        <el-table-column
          label="检测结果"
          align="center"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.TestData"
              placeholder="请选择检测结果"
              style="width: 100%"
              required
            >
              <el-option
                v-for="item in testResultOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <!-- 编辑模式显示检测人员列 -->
        <el-table-column
          v-if="isEditMode"
          label="检测人员"
          align="center"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.TestPerson"
              placeholder="请选择检测人员"
              style="width: 100%"
              required
            >
              <el-option
                v-for="item in inspectorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="测试时间"
          align="center"
        >
          <template #default="scope">
            <el-input
              v-model="scope.row.TestTime"
              readonly
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="是否上传"
          align="center"
        >
          <template #default="scope">
            <el-select
              v-model="scope.row.isUploaded"
              placeholder="请选择上传状态"
              style="width: 100%"
              required
            >
              <el-option label="已上传" value="已上传" />
              <el-option label="未上传" value="未上传" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="80"
        >
          <template #default="scope">
            <el-button
              type="text"
              @click="deleteAddRow(scope.$index)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗操作区 -->
      <div class="dialog-footer">
        <el-button
          @click="addNewRow"
          v-if="!isEditMode"
          type="success"
        >
          新增一行
        </el-button>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBatchData" :loading="saveLoading">
          {{ isEditMode ? '保存修改' : '批量保存' }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 查看弹窗 -->
    <el-dialog
      title="查看检测数据"
      v-model="viewDialogVisible"
      width="600px"
      append-to-body
      :modal="true"
      :close-on-click-modal="false"
    >
      <div class="view-container">
        <el-form :model="viewRow" label-width="120px">
          <el-form-item label="检测项目">
            {{ getInspectionItemLabel(viewRow.TestName) }}
          </el-form-item>
          <el-form-item label="批次号">
            {{ viewRow.Lot }}
          </el-form-item>
          <!-- 查看弹窗中的检测结果 - 已添加颜色 -->
          <el-form-item label="检测结果">
            <span :style="viewRow.TestData === 'OK' ? 'color: #10b981; font-weight: bold;' : 'color: #ef4444; font-weight: bold;'">
              {{ getTestResultLabel(viewRow.TestData) }}
            </span>
          </el-form-item>
          <el-form-item label="检测人员">
            {{ getInspectorLabel(viewRow.TestPerson) }}
          </el-form-item>
          <el-form-item label="测试时间">
            {{ viewRow.TestTime }}
          </el-form-item>
          <el-form-item label="是否上传">
            <el-tag :type="viewRow.isUploaded === '已上传' ? 'success' : 'warning'">
              {{ viewRow.isUploaded }}
            </el-tag>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer" style="text-align: center">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElSelect,
  ElOption,
  ElInput,
  ElMessage,
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElMessageBox,
  ElTag
} from 'element-plus'
import 'element-plus/dist/index.css'

export default {
  name: 'QualityInspection1',
  components: {
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElSelect,
    ElOption,
    ElInput,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
    ElTag
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    // 表格加载状态
    const tableLoading = ref(false)
    // 新增/编辑弹窗显示状态
    const addDialogVisible = ref(false)
    // 查看弹窗显示状态
    const viewDialogVisible = ref(false)
    // 新增表格数据
    const addTableData = ref([])
    // 保存加载状态
    const saveLoading = ref(false)
    // 选中的行（批量操作用）
    const selectedRows = ref([])
    // 编辑模式标记
    const isEditMode = ref(false)
    // 当前编辑/查看的行数据
    const currentRow = ref(null)
    // 查看弹窗数据
    const viewRow = ref({})
    // 查询表单
    const searchForm = ref({
      TestName: '',    // 检测项目
      Lot: '',         // 批次号
      TestPerson: '',  // 检测人员
      isUploaded: ''   // 上传状态（字符串类型）
    })
    // 批量新增表单（存储检测项目和检测人员）
    const batchForm = ref({
      TestName: '',
      TestPerson: ''
    })

    // 检测项目下拉选项
    const inspectionItemOptions = ref([
      { label: '表面张力', value: 'atm.qc.inspect.surface_tension' },
      { label: '百格', value: 'atm.qc.inspect.cross_cut' },
      { label: '丙酮', value: 'atm.qc.inspect.acetone_wipe' },
      { label: '孔隙率', value: 'porosity' },
      { label: '胶带测试', value: 'tapeTest' }
    ])

    // 检测结果下拉选项
    const testResultOptions = ref([
      { label: 'OK', value: 'OK' },
      { label: 'NG', value: 'NG' }
    ])

    // 检测人员下拉选项
    const inspectorOptions = ref([
      { label: '马惠玲', value: '马惠玲' },
      { label: '肖士营', value: '肖士营' },
      { label: '赵小松', value: '赵小松' },
      { label: '霍娟', value: '霍娟' },
      { label: '覃燕芳', value: '覃燕芳' },
      { label: '朱雅娟', value: '朱雅娟' },
      { label: '杜江艳', value: '杜江艳' },
      { label: '许利艳', value: '许利艳' },
      { label: '黄兰兰', value: '黄兰兰' },
      { label: '唐利明', value: '唐利明' },
      { label: '王亚楠', value: '王亚楠' }
    ])

    // 测试数据
    const testTableData = ref([
      {
        TestName: 'atm.qc.inspect.surface_tension',
        Lot: 'B20251120001',
        TestData: 'OK',
        TestPerson: '马惠玲',
        TestTime: '2025-11-20 09:30:00',
        isUploaded: '已上传'
      },
      {
        TestName: 'atm.qc.inspect.cross_cut',
        Lot: 'B20251120002',
        TestData: 'NG',
        TestPerson: '肖士营',
        TestTime: '2025-11-20 10:15:00',
        isUploaded: '未上传'
      },
      {
        TestName: 'atm.qc.inspect.acetone_wipe',
        Lot: 'B20251120003',
        TestData: 'OK',
        TestPerson: '赵小松',
        TestTime: '2025-11-20 11:00:00',
        isUploaded: '已上传'
      },
      {
        TestName: 'porosity',
        Lot: 'B20251120004',
        TestData: 'OK',
        TestPerson: '霍娟',
        TestTime: '2025-11-20 14:20:00',
        isUploaded: '未上传'
      },
      {
        TestName: 'tapeTest',
        Lot: 'B20251120005',
        TestData: 'NG',
        TestPerson: '覃燕芳',
        TestTime: '2025-11-20 15:40:00',
        isUploaded: '已上传'
      }
    ])

    /**
     * 格式化日期时间
     */
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      const second = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }

    /**
     * 根据数据库TestName值获取检测项目中文标签
     */
    const getInspectionItemLabel = (value) => {
      const item = inspectionItemOptions.value.find(item => item.value === value)
      return item ? item.label : value
    }

    /**
     * 根据数据库TestData值获取检测结果中文标签
     */
    const getTestResultLabel = (value) => {
      const item = testResultOptions.value.find(item => item.value === value)
      return item ? item.label : value
    }

    /**
     * 根据数据库TestPerson值获取检测人员中文标签
     */
    const getInspectorLabel = (value) => {
      const item = inspectorOptions.value.find(item => item.value === value)
      return item ? item.label : value
    }

    /**
     * 创建空行数据
     */
    const createEmptyRow = () => {
      return {
        TestName: batchForm.value.TestName,
        Lot: '',
        TestData: '',
        TestPerson: batchForm.value.TestPerson,
        TestTime: formatDate(new Date()),
        isUploaded: '未上传'
      }
    }

    /**
     * 过滤表格数据
     */
    const filteredTableData = computed(() => {
      return tableData.value.filter(row => {
        if (searchForm.value.TestName && row.TestName !== searchForm.value.TestName) return false
        if (searchForm.value.Lot && !row.Lot.includes(searchForm.value.Lot)) return false
        if (searchForm.value.TestPerson && row.TestPerson !== searchForm.value.TestPerson) return false
        if (searchForm.value.isUploaded && row.isUploaded !== searchForm.value.isUploaded) return false
        return true
      })
    })

    /**
     * 打开新增弹窗
     */
    const handleOpenDialog = () => {
      isEditMode.value = false
      batchForm.value = { TestName: '', TestPerson: '' }
      addTableData.value = [createEmptyRow()]
      addDialogVisible.value = true
    }

    /**
     * 打开编辑弹窗
     */
    const handleEdit = (row) => {
      isEditMode.value = true
      currentRow.value = { ...row }
      addTableData.value = [currentRow.value]
      addDialogVisible.value = true
    }

    /**
     * 打开查看弹窗
     */
    const handleView = (row) => {
      viewRow.value = { ...row }
      viewDialogVisible.value = true
    }

    /**
     * 删除行数据
     */
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除这条数据吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        tableData.value = tableData.value.filter(item => !(
          item.Lot === row.Lot &&
          item.TestTime === row.TestTime
        ))
        ElMessage.success('删除成功')
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }

    /**
     * 重置查询条件
     */
    const resetSearch = () => {
      searchForm.value = {
        TestName: '',
        Lot: '',
        TestPerson: '',
        isUploaded: ''
      }
    }

    /**
     * 获取表格数据
     */
    const fetchTableData = async () => {
      try {
        tableLoading.value = true
        const response = await axios.get('/api/table_wgjy/search_data_jiance1').catch(err => err)
        console.log("API返回数据：", response, response.data)
        tableData.value = response.data || []
        
        tableData.value = tableData.value.map(item => ({
          ...item,
          TestData: item.TestData ?? ''
        }))
        
      } catch (error) {
        console.warn('使用测试数据：', error.message)
        ElMessage.warning('接口不可用，展示测试数据')
        tableData.value = testTableData.value
      } finally {
        tableLoading.value = false
      }
    }

    /**
     * 新增一行
     */
    const addNewRow = () => {
      if (!batchForm.value.TestName || !batchForm.value.TestPerson) {
        ElMessage.warning('请先选择检测项目和检测人员')
        return
      }
      addTableData.value.push(createEmptyRow())
    }

    /**
     * 删除新增行
     */
    const deleteAddRow = (index) => {
      addTableData.value.splice(index, 1)
      if (addTableData.value.length === 0) {
        addTableData.value.push(createEmptyRow())
      }
    }

    /**
     * 选中行变化
     */
    const handleSelectionChange = (val) => {
      selectedRows.value = val
    }

    /**
     * 批量保存数据
     */
    const saveBatchData = async () => {
      if (!isEditMode && (!batchForm.value.TestName || !batchForm.value.TestPerson)) {
        ElMessage.warning('请选择检测项目和检测人员')
        return
      }

      // ### 核心修复逻辑开始 ###
      // 在保存前，强制同步 batchForm 的最新值到 addTableData 的每一行
      if (!isEditMode) {
        addTableData.value = addTableData.value.map(row => ({
          ...row,
          TestName: batchForm.value.TestName,
          TestPerson: batchForm.value.TestPerson,
        }))
      }
      // ### 核心修复逻辑结束 ###

      console.log("DDDDD",addTableData.value,batchForm.value.TestName)
      for(let i=0;i<addTableData.value.length;i++){
        if(addTableData.value[i].TestName == ""){
          addTableData.value[i].TestName = batchForm.value.TestName
          addTableData.value[i].TestPerson = batchForm.value.TestPerson
        }
      }
      const valid = addTableData.value.every(row => {
        return row.Lot && row.TestData && row.isUploaded && row.TestName && row.TestPerson
      })

      if (!valid) {
        ElMessage.warning('请完善所有必填项数据')
        return
      }

      try {
        saveLoading.value = true
        // 模拟API调用
        const response = await axios.post('/api/table_wgjy/insert_db_info', addTableData.value);
        // if (response.data.success) {
          ElMessage.success("提交成功！！！")
        
      } catch (error) {
        console.error('保存API请求失败：', error)
        ElMessage.warning(isEditMode.value ? '保存接口不可用，已本地修改' : '保存接口不可用，已本地新增')
      } finally {
        // 无论API是否成功，都更新本地表格
        if (isEditMode.value) {
          const index = tableData.value.findIndex(item => 
            item.Lot === currentRow.value.Lot &&
            item.TestTime === currentRow.value.TestTime
          )
          if (index !== -1) {
            tableData.value[index] = { ...addTableData.value[0] }
          }
        } else {
          addTableData.value.forEach(row => {
            tableData.value.unshift({ ...row })
          })
        }

        saveLoading.value = false
        addDialogVisible.value = false
        addTableData.value = []
        currentRow.value = null
      }
    }

    // 组件挂载后获取数据
    onMounted(() => {
      fetchTableData()
    })

    // 暴露所有需要的属性和方法
    return {
      tableData,
      tableLoading,
      addDialogVisible,
      viewDialogVisible,
      addTableData,
      saveLoading,
      isEditMode,
      currentRow,
      viewRow,
      searchForm,
      batchForm,
      inspectionItemOptions,
      testResultOptions,
      inspectorOptions,
      filteredTableData,
      getInspectionItemLabel,
      getTestResultLabel,
      getInspectorLabel,
      handleOpenDialog,
      handleEdit,
      handleView,
      handleDelete,
      resetSearch,
      fetchTableData,
      addNewRow,
      deleteAddRow,
      handleSelectionChange,
      saveBatchData
    }
  }
}
</script>

<style scoped>
.quality-inspection {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1989fa;
  margin: 0;
}

/* 按钮样式优化 */
::v-deep(.el-button) {
  cursor: pointer;
}

/* 弹窗样式优化 */
::v-deep(.el-dialog) {
  z-index: 9999 !important;
}

::v-deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

/* 表格样式优化 */
::v-deep(.el-table) {
  overflow-y: auto;
}

::v-deep(.el-table__header-wrapper) {
  background: #fff;
}

::v-deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
}

::v-deep(.el-table td),
::v-deep(.el-table th) {
  padding: 12px 0;
}

::v-deep(.el-select),
::v-deep(.el-input) {
  width: 100%;
}

/* 查看弹窗样式 */
.view-container {
  padding: 10px 0;
}

::v-deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 自定义文本颜色类 */
::v-deep(.text-green-600) {
  color: #10b981; /* emerald-500 */
}
::v-deep(.text-red-600) {
  color: #ef4444; /* red-500 */
}
::v-deep(.font-bold) {
  font-weight: 700;
}
</style>